import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Modal, Button, Form, message, Row, Col, Upload,} from 'antd';
import PropTypes from "prop-types";
import { getToken } from "@/utils/utils";
import { fromJS } from 'immutable';
import DetailModal from './exportDetailModel';
import { exportExlsx } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common';

const mapStateToProps = (state: any) => ({
  HandsetMng: state.HandsetMng,
})
class ExportModal extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      fileList: [],
      detailVisible: false,
      handSetList: [],//存储校验后的手持机list信息
      showErr: false,
    };
  }
  //批量保存
  handleSubmit = () => {
   const {handSetList,fileList}=this.state;
   if(!fileList.length)return message.warning('未导入数据，无法提交保存！');
   if(!handSetList.length)return message.warning('导入数据为空，无法提交保存！');
    for( let i = 0; i<handSetList.length; i++){
      if(handSetList[i].result !== 0 ){
        message.warning('导入数据有误，无法提交保存！');
        return
      }else{
        continue
      }
    }
    this.batchSave();
  }

  batchSave = () => {
    const { dispatch,} = this.props;
    const {handSetList} = this.state;
    this.setState({
      loading: true
    })
    const param = {
      handheldsList: handSetList
    }
    const list = [...handSetList]
    dispatch({
      type: 'HandsetMng/postListList',
      payload: {
        url: '/msalcohollock/handhelds/batch',list
        // ...handSetList,
        // ...param,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('批量保存成功');
          this.close();
          dispatch({
            type: 'HandsetMng/getFetchPage',
            payload: { 
              url: '/msalcohollock/handhelds/page',
            },
          });
        }
        this.setState({
          loading: false
        })
      }
    })
  }

  close = () => {
    const { closeModal } = this.props;
    this.setState({
      fileList: [],
      handSetList: [],
      showErr: false,
    })
    closeModal();
  }
  removeList = (fileList: any, file: any) => {
    const newList = fromJS(fileList).toJS();
    const i = newList.findIndex(e => e.uid === file.uid);
    if (i >= 0) {
      newList.splice(i, 1);
    }
    return newList;
  };
  // 文件删除
  handleRemove = (file: any) => {
    const { fileList } = this.state;
    const newList = this.removeList(fileList, file);
    this.setState({ fileList: newList });
  };
    // 文件上传前校验
    beforeFileUpload = (file:any) => {
      const {fileList}=this.state;
      const isXlsx = file.name.endsWith('.xlsx');
      if (!isXlsx) {
        message.error('请上传.xlsx格式文件');
        return false;
      }
  
      if(fileList.length === 1){
        message.warning('只能上传一个文件！');
        return false;
      }
      return true;
    };
    handleChange = (info: any) => {
      const { fileList, file } = info;
      const newList = this.removeList(fileList, file);
      if (
        file.status === 'done' &&
        file.response &&
        file.response.statusCode === '0' &&
        file.response.data
      ) {
        message.success(`${file.name} 上传成功`);
        this.setState({
          handSetList: file.response.data?.checkList??[],
          showErr: Number(file.response.data?.checkResult) !== 0,
        });
      } else if (file.status === 'done' && file.response && file.response.statusCode !== '0') {
        if(file.response.data){
          message.error(file.response.data +'在'+ file.response.statusMessage);
        }else{
          message.error(file.response.statusMessage);
        }
        this.setState({ fileList: []})
        // this.setState({ fileList: newList });
        return;
      } else if (file.status === 'removed') {
        this.setState({
          showErr: false,
          handSetList: [],
        });
        message.success('删除成功');
        return;
      } else if (file.status === 'error') {
        message.error(`${file.name} 上传失败`);
        this.setState({ fileList: newList });
        return;
      } else if (!file.status) {
        this.setState({ fileList: newList });
        return;
      }
      this.setState({ fileList });
    };
    handleDetail =()=>{
      this.setState({detailVisible:true})
    }
    closeModal=()=>{
      this.setState({detailVisible:false})
    }
    exportTable = () => {
      exportExlsx({
        table: [['手持机编号（必填）', '手持机名称'], ['handset001', '机名001']],
        name: '手持机批量上传模板'
      });
    };
  render() {
    const { loading,detailVisible,handSetList,showErr } = this.state
    const {modalVisible}=this.props;
    const domain = window.g.url;
    const uploadUrl = '/msalcohollock/handhelds/batch/check';//批量校验手持机
    const uploadStr = `${domain}${uploadUrl}`;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
          确定
        </Button>
      </div>
    )
    const props = {
      action: uploadStr,
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders() },
      multiple: false,
      accept: '.xls,.xlsx,application/vnd.ms-excel',
      onRemove: this.handleRemove,
      beforeUpload: this.beforeFileUpload,
      onChange: this.handleChange,
    };
    return (
      <Modal
        title={'批量导入'}
        footer={footer}
        visible={modalVisible}
        width={700}
        onCancel={this.close}
      >
       <Row gutter={24}>
         <Col span={16}>
          <Form>
            <Form.Item
            label='批量导入设备' name={'uploadFile'} rules={[{required:true}]}>
          <Upload {...props} fileList={this.state.fileList}>
              <Button type="primary" style={{width:'200px'}}>
                 点击上传
              </Button>
          </Upload>
          <div style={{fontSize: 12, color: "grey",width:'200px'}}>只能上传xls,xlsx格式的Excel文件</div>
          {showErr ? <div style={{ fontSize: 12, color: 'red' }}>导入数据有误</div> : null}
          </Form.Item>
          </Form>
         </Col>
         <Col span={4}>
              <Button type="primary" shape="round" onClick={this.exportTable}>
                 下载模版
              </Button>
         </Col>
         <Col span={4}>
              <Button type="primary" shape="round" onClick={()=>{this.handleDetail()}}>
                 导入详情
              </Button>
         </Col>
       </Row>
       <DetailModal
         handSetList={handSetList}
         modalVisible={detailVisible}
         closeModal={this.closeModal}
         >
        </DetailModal>
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(ExportModal);
